package com.lagou.web.servlet;

import com.lagou.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //1.创建磁盘文件工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();

            //2.创建文件上传核心类
            ServletFileUpload upload=new ServletFileUpload(factory);
            //2.1 设置上传文件的编码
            upload.setHeaderEncoding("utf-8");
            //2.2 判断表单是否是文件上传表单
            boolean multipartContent = upload.isMultipartContent(req);
            if(multipartContent){

                List<FileItem> list = upload.parseRequest(req);
                if(list!=null){

                    //遍历集合
                    for(FileItem item:list){
                        boolean formField = item.isFormField();
                        if(formField){
                            String fieldName = item.getFieldName();
                            String fieldValue = item.getString("utf-8");

                            System.out.println(fieldName+"="+fieldValue);
                        }else {
                            String fileName = item.getName();
                            String newFileName = UUIDUtils.getUUID() + "_" + fileName;
                            InputStream in = item.getInputStream();


                            String realPath = this.getServletContext().getRealPath("/");

                            String webappsPath = realPath.substring(0, realPath.indexOf("lagou_edu_home"));




                            FileOutputStream out=new FileOutputStream(webappsPath+"/upload/"+newFileName);
                            IOUtils.copy(in,out);
                            out.close();
                            in.close();

                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
